package com.zb.web.controller;

import com.zb.model.*;
import com.zb.service.ManagerService;
import com.zb.service.OrderService;
import com.zb.service.ReceiveAreaService;
import com.zb.service.impl.GoodsServiceImpl;
import com.zb.service.impl.ShopCartServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/web")
public class OrderController {

	@Autowired
	private OrderService ls;
	
	@Autowired
	private ShopCartServiceImpl scs;
	
	@Autowired
	private ManagerService ms;
	
	@Autowired
	private GoodsServiceImpl gs;
	
	@Autowired
	private ReceiveAreaService lls;
	/**
	 * 获取个人订单，并跳转至订单页
	 * @param userid
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/getorders")
	public String loginInspect(String userid,HttpSession session,HttpServletRequest request) {
		if(session.getAttribute("userid")==null) {
			return "login";
		}else {
			userid=session.getAttribute("userid").toString();
			System.out.println("----------"+userid);
			List<TOrder> orderList=ls.findOrdersService(userid);
			List<TOrder> orderPayList= new ArrayList<>();
			List<TOrder> orderEmitList= new ArrayList<>();
			List<TOrder> orderTakeList= new ArrayList<>();
			List<TOrder> orderEvalList= new ArrayList<>();
			if(orderList!=null) {
				session.setAttribute("orderList", orderList);
				for(int i=0;i<orderList.size();i++) {
					String status = orderList.get(i).getZhuangtai();
					if(status.equals("等待付款")) {
						orderPayList.add(orderList.get(i));
					}else if(status.equals("等待发货")) {
						orderEmitList.add(orderList.get(i));
					}else if(status.equals("等待收货")) {
						orderTakeList.add(orderList.get(i));
					}else if(status.equals("已签收")) {
						orderEvalList.add(orderList.get(i));
					}else {
						System.out.println("状态有误");
					}
				}
				
				session.setAttribute("orderPayList", orderPayList);
				session.setAttribute("orderEmitList", orderEmitList);
				session.setAttribute("orderTakeList", orderTakeList);
				session.setAttribute("orderEvalList", orderEvalList);
				
				return "udai_welcome";
			}else {
				JOptionPane.showMessageDialog(null, "未查询到订单");
				return "udai_welcome";
			}
		}
		//return "login";	
	}
	
	/**
	 * 获取某状态的订单
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/getordersByStatus")
	public String getordersByStatus(HttpSession session,HttpServletRequest request) {
		int status = Integer.parseInt(request.getParameter("status"));
		String st = "";
		switch(status) {
			case 0: st="等待付款";break;
			case 1: st="等待发货";break;
			case 2: st="运输中";break;
			case 3: st="已签收";break;
			default: break;
		}
		List<TOrder> orderList=ls.findAllOrdersService();
		System.out.println("************找到了这些orderList："+orderList);
		System.out.println("状态是："+st);
		List<TOrder> newOrderList = new ArrayList<>();
		for(int i=0;i<orderList.size();i++) {
			if(orderList.get(i).getZhuangtai().equals(st)) {
				newOrderList.add(orderList.get(i));
			}
		}
		session.setAttribute("statusOrderList", newOrderList);
		
		return "admin/statusOrder";
	}
	
	/**
	 * 修改订单状态
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/reorderStatus")
	public String reorderStatus(String orderid,HttpSession session,HttpServletRequest request) {
		String orderId = request.getParameter("orderId");
		int oldStatus = Integer.parseInt(request.getParameter("oldStatus"));
		int newStatus = Integer.parseInt(request.getParameter("newStatus"));
		if(newStatus-oldStatus>1) {
			JOptionPane.showMessageDialog(null, "不能越级进行操作");
			return "udai_welcome";
		}
		System.out.println("orderID is"+orderId+"新老状态为"+oldStatus+","+newStatus);
		if(oldStatus==0&&newStatus==1) {
			ls.reOrdersService(orderId, "等待发货");
		}else if(oldStatus==1&&newStatus==2) {
			ls.reOrdersService(orderId, "等待收货");
		}else if(oldStatus==2&&newStatus==3) {
			ls.reOrdersService(orderId, "已签收");
		}
		
		return "admin/ok";	
	}
	
	/**
	 * 获取个人订单，并跳转至订单页
	 * @param userid
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/getordersDetail")
	public String getOrderDetail(String userid,HttpSession session,HttpServletRequest request) {
		String orderId = request.getParameter("orderId");
		System.out.println("orderId="+orderId);
		List<TOrderDetail> todList = ls.findOrderDetailService(orderId);
		session.setAttribute("todList", todList);
		System.out.println("我传过去的todList 是"+todList);
		return "goods/orderDetail";
	}
	
	/**
	 * 获取个人订单，并跳转至订单页
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/getOrderAccount")
	public String getOrderAccount(HttpSession session,HttpServletRequest request) {
		String dateBegin = request.getParameter("dateBegin");
		String dateEnd = request.getParameter("dateEnd");
		
		
		
		return "goods/orderDetail";
	}
	
	/**
	 * 获取个人订单，并跳转至订单页
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/getOrderBeginEnd")
	public String getOrderBeginEnd(HttpSession session,HttpServletRequest request) {
		String dateBegin = request.getParameter("dateBegin");
		String dateEnd = request.getParameter("dateEnd");
		
		System.out.println("开始结束时间为："+dateBegin+"----"+dateEnd);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		 
		try {
			Date date1 = format.parse(dateBegin);
			Date date2 = format.parse(dateEnd);
			
			int compareTo = date1.compareTo(date2);
			
			System.out.println(compareTo);
			if(compareTo==1) {
				System.out.println("dateBegin小于dateEnd");
				JOptionPane.showMessageDialog(null, "输入的开始时间和结束时间不合法，请重新选择");
				return "admin/orderlist";
			}else {
				System.out.println("时间输入合法");
				List<TOrder> orderList = ls.findOrdersByTimeService(date1, date2);
				session.setAttribute("orderList", orderList);
				if(orderList!=null) {
					double saleSum=0,profitSum=0;//计算该时间段的销售额和盈利额
					
					for(int i=0;i<orderList.size();i++) {
						String orderId=orderList.get(i).getOrderids();
						saleSum+=ls.getOrderSale(orderId);
						profitSum+=ls.getOrderProfit(orderId);
						System.out.println("该订单的销售额是："+ls.getOrderSale(orderId));
						System.out.println("该订单的盈利额是："+ls.getOrderProfit(orderId));
					}
//					List<TOrderDetail> oderDetail
					//计算这个时间段的销售额、盈利额
					
					System.out.println("销售总额是："+saleSum);
					System.out.println("盈利总额是："+profitSum);
					
					session.setAttribute("saleSum", saleSum);
					session.setAttribute("profitSum", profitSum);
				}
			}
			
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return "admin/orderlist";
	}
	
	/**
	 * @param orderid
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/qxorder")
	public String qxorder(String orderid,HttpSession session,HttpServletRequest request) {
		
		boolean flag=ls.qxOrdersService(orderid);
		if(flag==false) {
			//JOptionPane.showMessageDialog(null, "ɾ��ʧ��");
			//response.sendRedirect("Login.jsp");
			return "udai_welcome";
		}else {
			//JOptionPane.showMessageDialog(null, "ɾ���ɹ�");
			return"udai_welcome";
		}
			
	}
	

	@RequestMapping("/addorder不再使用")
	public String addorder(HttpSession session,HttpServletRequest request) {
		TOrder torder=new TOrder();
		String id=UUID.randomUUID().toString();
		torder.setOrderids(id);
		torder.setPhone(request.getParameter("phone"));
		torder.setTarget(request.getParameter("target"));
		torder.setUserid(session.getAttribute("userid").toString());
		torder.setGoodsname(request.getParameter("goodsname"));
		torder.setDanjia(Integer.parseInt(request.getParameter("danjia")));
		torder.setShuliang(Integer.parseInt(request.getParameter("shuliang")));
		torder.setShifukuan(Integer.parseInt(request.getParameter("shifukuan")));
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
		Date date = new Date();
		//String s = simpleDateFormat.format(date);
		torder.setTime(date);
		torder.setZhuangtai("等待发货");
		torder.setShoujianrenname(request.getParameter("shoujianrenname"));
		boolean flag=ls.addOrdersService(torder);
		if(flag==false) {
			//JOptionPane.showMessageDialog(null, "���ʧ��");
			//response.sendRedirect("Login.jsp");
			return "udai_welcome";
		}else {
			//JOptionPane.showMessageDialog(null, "��ӳɹ�");
			return"udai_welcome";
		}
			
	}
	
	/**
	 * 这里开始正式添加order/orderDetail/,对shopcart内容进行修改
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/addorderX")
	public String addorderX(HttpSession session,HttpServletRequest request) {
		
		String userid = (String)session.getAttribute("userid");
		//获取到订单内容，同时将其持久化
		List<TOrderDetail> todList = (List<TOrderDetail>) session.getAttribute("orderDetailList");
		//库存检查
		for(int i=0;i<todList.size();i++) {
			//商品库存数量检查与更新
			TOrderDetail tod = todList.get(i);
			//ls.addOrderDetailService(tod);
			
			//开始从购物车中移除
			String goodsId = tod.getGoodsId();
			int count = tod.getNumber();
			TGoods tg=gs.selectGoodsByIdService(goodsId);
			System.out.println("the goods is " + tg);
			int oldStock=tg.getGoodsStock();
			TGoods goods=new TGoods();
			goods.setGoodsId(goodsId);
			if(oldStock-count<0) {
				System.out.println("库存不足了");
				JOptionPane.showMessageDialog(null, "库存不足,请您重新查看书目数量。");
				return "shopcart";
			}
		}
		double shifukuan=0;
		for(int i=0;i<todList.size();i++) {
			TOrderDetail tod = todList.get(i);
			System.out.println("将要添加的订单内容是："+tod+"--------");
			ls.addOrderDetailService(tod);
			//计算该订单的实付款，即销售额
			shifukuan+=tod.getPrice()*tod.getNumber();
			System.out.println("这件商品实付款是："+"--------->"+tod.getPrice()*tod.getNumber()+"当前计算的总价是："+shifukuan);
			//开始从购物车中移除
			String goodsId = tod.getGoodsId();
			//System.out.println(goodsId+"***---***"+userid);
			List<TGoodsInShopCart> shopcartList = scs.delGoodsIntoShopCartService(goodsId,userid);
			session.setAttribute("shopcartList", shopcartList);
			System.out.println("购物车列表已经传上去了");	
			
			//商品库存数量检查与更新
			int count = tod.getNumber();
			TGoods tg=gs.selectGoodsByIdService(goodsId);
			//System.out.println("the goods is " + tg);
			int oldStock=tg.getGoodsStock();
			TGoods goods=new TGoods();
			goods.setGoodsId(goodsId);
			if(oldStock-count<0) {
				System.out.println("库存不足了");
				JOptionPane.showMessageDialog(null, "库存不足,请您重新查看书目数量。");
				return "shopcart";
			}else {
				goods.setGoodsStock(oldStock-count);
				ms.reStock(goods);
				//这时候减库存，但还没有付款
			}
		}
		session.removeAttribute("orderDetailList");
		//生成订单
		String orderid="";
		if(todList!=null) {
			orderid = todList.get(0).getOrderId();
		}
		TOrder torder=new TOrder();
		torder.setOrderids(orderid);
		torder.setPhone(request.getParameter("phone"));
		torder.setTarget(request.getParameter("target"));
		torder.setUserid(session.getAttribute("userid").toString());
		torder.setShifukuan(shifukuan);
		System.out.println("我添加进去的这个实付款是"+shifukuan);
		//torder.setGoodsname(request.getParameter("goodsname"));
		//torder.setDanjia(Integer.parseInt(request.getParameter("danjia")));
		//torder.setShuliang(Integer.parseInt(request.getParameter("shuliang")));
		
		//钱数还没有计算
		//torder.setShifukuan(Integer.parseInt(request.getParameter("shifukuan")));
		//SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
		Date date = new Date();
		//String s = simpleDateFormat.format(date);
		torder.setTime(date);
		torder.setUpdatetime(date);
		torder.setZhuangtai("等待付款");
		torder.setShoujianrenname(request.getParameter("shoujianrenname"));
		boolean flag=ls.addOrdersService(torder);
		if(flag==false) {
			JOptionPane.showMessageDialog(null, "订单生成失败，请检查提交信息");
			//response.sendRedirect("Login.jsp");
			//return "udai_welcome";
		}else {
			JOptionPane.showMessageDialog(null, "订单已生成");
			//return"udai_welcome";
		}
		
		return"udai_welcome";
	}
	
	/**
	 * 添加订单的准备工作，确认订单(多个商品)
	 * @param session
	 * @param request
	 * @return
	 */
	@RequestMapping("/addorder_goods")
	public String addorder_goods(HttpSession session,HttpServletRequest request) {
		String orderData = request.getParameter("orderData");
		System.out.println("---------->"+orderData);
		String []orderBooks = orderData.split(",");
		for (String string : orderBooks) {
			System.out.println("--->"+string);
		}
		List<TOrderDetail> todList = new ArrayList<>();
		//订单详情
		
		//订单
		//TOrder torder=new TOrder();
		//先生成一个伪订单
		double sum = 0;
		String orderId=UUID.randomUUID().toString();
		for(int i=0;i<orderBooks.length;i++) {
			String []bookInfo = orderBooks[i].split(" ");
			System.out.println("查看一下bookInfo："+bookInfo.length);
			String goodsId = bookInfo[0];
			double price = Double.parseDouble(bookInfo[1]);
			int count = Integer.parseInt(bookInfo[2]);
			String imgPth = bookInfo[3];
			System.out.println("订单中该书为："+goodsId+",单价为："+price+"元,数量为："+count+"图片路径是："+imgPth);
			
			//商品库存数量检查
			TGoods tg=gs.selectGoodsByIdService(goodsId);
			System.out.println("the goods is " + tg);
			int oldStock=tg.getGoodsStock();
			TGoods goods=new TGoods();
			goods.setGoodsId(goodsId);
			if(oldStock-count<0) {
				System.out.println("库存不足了");
				JOptionPane.showMessageDialog(null, "库存不足,请您重新查看书目数量。");
				return "shopcart";
			}else {
				//goods.setGoodsStock(oldStock-count);
				//ms.reStock(goods);
				//这时候还不能减库存，还没有付款
			}
			TOrderDetail tod = new TOrderDetail();
			//填写订单详情信息
			tod.setOrderId(orderId);
			tod.setGoodsId(goodsId);
			tod.setPrice(price);
			tod.setNumber(count);
			tod.setImgPth(imgPth);
			sum = sum + count*price;
			//此时先不往数据库中添加
			//ls.addOrderDetailService(tod);
			
			//session.setAttribute("orderIdNow", orderId);
			todList.add(tod);
			
			//从购物车中删除,但是现在先不进行删除
//			String userid = (String)session.getAttribute("userid");
//			System.out.println(goodsId+"***---***"+userid);
//			List<TGoodsInShopCart> shopcartList = scs.delGoodsIntoShopCartService(goodsId,userid);
//			session.setAttribute("shopcartList", shopcartList);
//			System.out.println("购物车列表已经传上去了");	
			
		}
		session.setAttribute("orderIdNow", orderId);
		session.setAttribute("orderDetailList", todList);
		request.setAttribute("sum",sum);
		System.out.println("我传过去的orderDetailList是："+todList);
		
		String userid=session.getAttribute("userid").toString();
		List<TReceiveArea> areaList=lls.selectAreaService(userid);
		if(areaList!=null) {
			session.setAttribute("areaList", areaList);
			System.out.println("我传过去的areaList是："+areaList);
			//return "udai_address";
		}else {
			System.out.println("没有areaList");
			//return "udai_address";
		}

		return "shopcart_pay";
	}
	
}
